import { Inject, Injectable, Optional, RendererFactory2, TemplateRef } from '@angular/core';
import { ComponentLoaderFactory } from 'ngx-bootstrap/component-loader';
import { BsModalRef, BsModalService, ModalOptions, MODAL_CONFIG_DEFAULT_OVERRIDE } from 'ngx-bootstrap/modal';

@Injectable()
export class AppBsModalService extends BsModalService {

    constructor(
        rendererFactory: RendererFactory2,
        private clf2: ComponentLoaderFactory,
        @Optional() @Inject(MODAL_CONFIG_DEFAULT_OVERRIDE) private modalDefaultOption2: ModalOptions) {
        super(rendererFactory, clf2, modalDefaultOption2);

        this.init();
    }

    init() {
        this.onShown.subscribe(() => {
            this.setZIndexes();
        });

        this.onHidden.subscribe(() => {
            let modalBackdrops = document.querySelectorAll('.modal-backdrop.fade.show');
            if (modalBackdrops.length > 0) {
                let currentBodyClass = document.body.className;
                if (currentBodyClass.indexOf('modal-open') < 0) {
                    document.body.className = currentBodyClass + '  modal-open';
                }
            }
        });
    }


    setZIndexes(): void {
        let modalBackdrops = document.querySelectorAll('.modal-backdrop.fade.show');
        let modalBaseZIndex = 1050;
        let modalsLength = modalBackdrops.length;
        let newZIndex = modalBaseZIndex + modalsLength * 2;

        let modals = document.querySelectorAll('.modal.fade');
        (modals[modals.length - 1] as HTMLElement).style.zIndex = newZIndex.toString();
        (modalBackdrops[modalBackdrops.length - 1] as HTMLElement).style.zIndex = (newZIndex - 1).toString();
    }
}
